﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Banks.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using System.Linq;
using System.Threading;

namespace mozhi.smarterp.Finance.Banks
{
    public class BankAccountRepository : EfCoreRepository<FinanceDbContext, BankAccount, Guid>, IBankAccountRepository
    {
        public BankAccountRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(string keyword, string number, string name, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<BankAccount>().AsNoTracking()
             .WhereIf(!keyword.IsNullOrEmpty(), x => x.Name.Contains(keyword) || x.Number.Contains(keyword))
             .WhereIf(!number.IsNullOrEmpty(), x => x.Number == number)
             .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
             .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
             .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<BankAccount>> GetPagedListAsync(string keyword, string number, string name, int maxResultCount , int skipCount , string sorting , CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<BankAccount>().AsNoTracking()
             .WhereIf(!keyword.IsNullOrEmpty(), x => x.Name.Contains(keyword) || x.Number.Contains(keyword))
             .WhereIf(!number.IsNullOrEmpty(), x => x.Number == number)
             .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
             .OrderByIf<BankAccount , IQueryable<BankAccount>>(!sorting.IsNullOrEmpty() , sorting)
             .PageBy(skipCount ,maxResultCount)
             .ToListAsync(cancellationToken);

            return entities;
        }

        public async Task<List<BankAccount>> GetListAsync(string keyword, string number, string name, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var bankAccounts = await dbContext.Set<BankAccount>().AsNoTracking()
            .WhereIf(!keyword.IsNullOrEmpty(), x => x.Name.Contains(keyword) || x.Number.Contains(keyword))
            .WhereIf(!number.IsNullOrEmpty(), x => x.Number == number)
            .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
            .ToListAsync(cancellationToken);

            return bankAccounts;
        }
    }
}
